<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
      xmlns:ngeo="http://geovocab.org/geometry#" 
      xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" 
      xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">

<xsl:output method="text" indent="yes" />

<xsl:template match="ngeo:MultiPolygon|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#MultiPolygon']]">
MULTIPOLYGON (<xsl:apply-templates select="./ngeo:polygonMember" />)
</xsl:template>

<xsl:template match="ngeo:polygonMember">
(<xsl:apply-templates select="descendant::ngeo:LinearRing|descendant::rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#LinearRing']]" />)<xsl:if test="position() != last()">,</xsl:if>
</xsl:template>

<xsl:template match="ngeo:Polygon|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#Polygon']]">
POLYGON (<xsl:apply-templates select="descendant::ngeo:LinearRing|descendant::rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#LinearRing']]" />)
</xsl:template>

<xsl:template match="ngeo:LinearRing|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#LinearRing']]">
(<xsl:apply-templates select="descendant::ngeo:posList" />)<xsl:if test="position() != last()">,</xsl:if>
</xsl:template>

<xsl:template match="ngeo:MultiLineString|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#MultiLineString']]">
MULTILINESTRING (<xsl:apply-templates select="./ngeo:lineStringMember" />)
</xsl:template>

<xsl:template match="ngeo:lineStringMember">
(<xsl:apply-templates select="descendant::ngeo:posList" />)<xsl:if test="position() != last()">,</xsl:if>
</xsl:template>

<xsl:template match="ngeo:LineString|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#LineString']]">
LINESTRING (<xsl:apply-templates select="descendant::ngeo:posList" />)
</xsl:template>

<xsl:template match="ngeo:MultiPoint|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#MultiPoint']]">
MULTIPOINT (<xsl:apply-templates select="./ngeo:pointMember" />)
</xsl:template>

<xsl:template match="ngeo:pointMember">
(<xsl:call-template name="coordinate" />)<xsl:if test="position() != last()">,</xsl:if>
</xsl:template>

<xsl:template match="ngeo:Point|rdf:Description[rdf:type[rdf:resource='http://geovocab.org/geometry#Point']]">
POINT(<xsl:call-template name="coordinate" />)
</xsl:template>

<xsl:template match="ngeo:posList">
<xsl:for-each select="./ngeo:Point|rdf:Description">
<xsl:call-template name="coordinate" /><xsl:if test="position() != last()">,</xsl:if>
</xsl:for-each>
</xsl:template>

<xsl:template name="coordinate">
<xsl:value-of select="./geo:long"/><xsl:text> </xsl:text><xsl:value-of select="./geo:lat"/>
</xsl:template>

</xsl:stylesheet>